package com.xiyou.week04.binaryReactor;

/**
 * @ClassName：DeleteNode
 * @Author：西柚
 * @Date：2022/1/22 11:54 下午
 * @Versiion：1.0
 */
public class DeleteNode {

    public TreeNode deleteNode(TreeNode root, int key) {
        if (root == null) {
            return null;
        }
        if (root.val == key) {
            if (root.left == null) return root.right;
            if (root.right == null) return root.left;
            TreeNode next = root.right;
            while (next.left != null) {
                next = next.left;
            }
            root.right = deleteNode(root.right, next.val);
            root.val = next.val;
            return root;
        }
        if (key < root.val) {
            root.left = deleteNode(root.left, key);
        } else {
            root.right = deleteNode(root.right, key);
        }
        return root;
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
